/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.logging.Level;
import java.util.logging.Logger;

/**

 @author Tomek
 */
public class FileSender {

	File fileToSend;
	FileInputStream fis;
	ByteBuffer buffer = ByteBuffer.allocate(128);
	SocketChannel socket;

	public FileSender(File fileToSend, SocketChannel socket) {
		this.fileToSend = fileToSend;
		this.socket = socket;
		try {
			fis = new FileInputStream(fileToSend);
			buffer.limit(0);
		} catch (FileNotFoundException ex) {
			Logger.getLogger(FileSender.class.getName()).log(Level.SEVERE, null, ex);
		}
	}

	public void readNextPart() throws IOException {
			buffer.clear();
			int fileLen = fis.available();
			int len = fis.read(buffer.array());
			if (len == -1) {
				len = fileLen;
			}
			buffer.limit(len);
	}

	public void sendNextPart() throws IOException {
			socket.write(buffer);
			socket.socket().getOutputStream().flush();
	}
}
